package com.zyiot.lbs;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources.NotFoundException;
import android.location.Location;
import android.os.Build.VERSION;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.EditorInfo;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;
import android.widget.Toast;

import com.umeng.analytics.MobclickAgent;
import com.zyiot.adapter.EshopAdapter;
import com.zyiot.bdapi.LBSCloudSearch;
import com.zyiot.model.Eshop;
import com.zyiot.utils.ZyUnit;

public class Test_TabListActivity extends Activity implements OnScrollListener {
	private boolean initSearchFlag = false;

	private RelativeLayout progress;
	private EshopAdapter adapter;
	private Handler load_Handler;
	private View moreView; // 加载更多页面
	private Context context;

	private ListView listView;
	private int start = 0;
	private static int refreshCnt = 0;
	private List<Eshop> list = new ArrayList<Eshop>();

	public static final int MSG_NET_TIMEOUT = 100;
	public static final int MSG_NET_STATUS_ERROR = 200;
	public static final int MSG_NET_SUCC = 1;
	private PopupWindow mPopupWindow;
	private String[] ArrayList_region;
	private HashMap<String, String> map_region;

	Spinner spinner_region;
	Spinner spinner_nearby;
	Spinner spinner_tags;
	private InitApplication app = null;
	private int page_index = 0;
	// listview item count
	private int count;
	private int total;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.test_layout_eshop_list);
		this.context = this;
		app = (InitApplication) this.getApplication();
		// Log.d("TEST",app.currlocation.getCity());
		listView = (ListView) findViewById(R.id.list_eshop_View);
		progress = (RelativeLayout) findViewById(R.id.relative_progress);
		moreView = getLayoutInflater().inflate(R.layout.item_list_footer, null);
		listView.addFooterView(moreView); // 添加底部view，一定要在setAdapter之前添加，否则会报错。
		initregionlist();

		initSpinner();

		// 加载搜索结果
		InitData();
		// popHandler.postDelayed(popRunnable, 500);

		adapter = new EshopAdapter(this, list, Test_TabListActivity.this, listView);
		if (adapter != null) {
			listView.setAdapter(adapter);
			listView.setItemsCanFocus(false);
		}
		EditText edit_search = (EditText) findViewById(R.id.edit_search);
		edit_search.setOnEditorActionListener(sumbit);

		Button btnMap = (Button) findViewById(R.id.btnmap);
		btnMap.setOnClickListener(listener);
		Button btnRefresh = (Button) findViewById(R.id.btnrefresh);
		btnRefresh.setOnClickListener(btn_refresh_listener);
		load_Handler = new Handler();
		listView.setOnScrollListener(this); // 设置listview的滚动事件
		listView.setOnItemClickListener(listView_eshop_item_listener);
	}

	private OnItemClickListener listView_eshop_item_listener = new OnItemClickListener() {
		@Override
		public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
			Eshop detail = new Eshop();
			detail = list.get(position);
			Intent intent = new Intent();
			intent.setClass(context, EshopDetailActivity.class);
			Bundle bundle = new Bundle();
			bundle.putSerializable("detail", detail);
			intent.putExtras(bundle);
			startActivity(intent);
		}

	};
	// 搜索回车按钮
	private OnEditorActionListener sumbit = new OnEditorActionListener() {
		@Override
		public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
			if (actionId == EditorInfo.IME_ACTION_SEND) {
				InitData();
				return true;
			}
			return false;
		}
	};

	// 初始化并分割区域列表
	private void initregionlist() {
		ArrayList_region = getResources().getStringArray(R.array.eshop);
		String[] region = ZyUnit.spiltArray(ArrayList_region, "[|]", 0);
		String[] geopoint = ZyUnit.spiltArray(ArrayList_region, "[|]", 1);
		map_region = new HashMap<String, String>();
		for (int i = 0; i < region.length; i++) {
			map_region.put(region[i], geopoint[i]);
		}
	};

	// 初始化下拉列表
	private void initSpinner() {
		spinner_region = (Spinner) findViewById(R.id.spinner_region);
		spinner_nearby = (Spinner) findViewById(R.id.spinner_nearby);
		spinner_tags = (Spinner) findViewById(R.id.spinner_tags);
		// 设置区域过滤下拉框
		ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.eshop_region, android.R.layout.simple_spinner_item);
		adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		spinner_region.setAdapter(adapter);
		spinner_region.setOnItemSelectedListener(tvlist_select_region_item_listener);

		// 设置区域范围下拉框
		adapter = ArrayAdapter.createFromResource(this, R.array.eshop_nearby, android.R.layout.simple_spinner_item);
		adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		spinner_nearby.setAdapter(adapter);
		spinner_nearby.setOnItemSelectedListener(tvlist_select_nearby_item_listener);

		// 设置商家类型下拉框
		adapter = ArrayAdapter.createFromResource(this, R.array.eshop_type, android.R.layout.simple_spinner_item);
		adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		spinner_tags.setAdapter(adapter);
		spinner_tags.setOnItemSelectedListener(tvlist_select_type_item_listener);

	}

	private void InitData() {
		page_index = 0;
		app.getList().clear();
		if (adapter != null) {
			adapter.notifyDataSetChanged();
		}
		search();
		InitApplication.getInstance().setHandler(mHandler);
	}

	// 地图刷新
	private OnClickListener btn_refresh_listener = new OnClickListener() {
		@Override
		public void onClick(View v) {
			// removeAllMarker();
			// initMapView();
			InitData();

		}
	};
	// 省市搜索按钮监听
	private OnItemSelectedListener tvlist_select_region_item_listener = new OnItemSelectedListener() {
		@Override
		public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
			if (initSearchFlag) {
				// spinner_nearby.setSelection(0);
				InitData();
			}
		}

		@Override
		public void onNothingSelected(AdapterView<?> arg0) {
		}

	};

	// 区域范围检索
	private OnItemSelectedListener tvlist_select_nearby_item_listener = new OnItemSelectedListener() {
		@Override
		public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
			if (initSearchFlag) {
				// spinner_region.setSelection(0);
				InitData();
			}
		}

		@Override
		public void onNothingSelected(AdapterView<?> arg0) {
		}

	};

	// 商家类型检索
	private OnItemSelectedListener tvlist_select_type_item_listener = new OnItemSelectedListener() {
		@Override
		public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
			if (initSearchFlag) {
				InitData();
			}
		}

		@Override
		public void onNothingSelected(AdapterView<?> arg0) {
			// TODO Auto-generated method stub
		}

	};

	// 按钮监听
	private OnClickListener listener = new OnClickListener() {
		@Override
		public void onClick(View arg0) {
			Intent intent = new Intent();
			intent.setClass(context, Test_TabListMapActivity.class);
			intent.putExtra("list", list.toArray());
			startActivityForResult(intent, 11);
			int version = Integer.valueOf(VERSION.SDK_INT);
			if (version >= 5) {
				overridePendingTransition(R.anim.zoom_in, R.anim.zoom_out);
			}
		}
	};

	// 云搜索handle
	private final Handler mHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			// closePopwindow();
			moreView.setVisibility(View.GONE);
			switch (msg.what) {
			case MSG_NET_TIMEOUT:
				break;
			case MSG_NET_STATUS_ERROR:
				break;
			case MSG_NET_SUCC:
				initSearchFlag = true;
				String result = msg.obj.toString();
//				Log.d("TEST", "JSON---->" + result);
				try {
					JSONObject json = new JSONObject(result);
					// parser(json);
					parser_V2(json);
				} catch (JSONException e) {
					e.printStackTrace();
				}
				break;

			}
		};

	};

	// 启动popwindow private Handler popHandler = new Handler(); private
	// Runnable popRunnable = new Runnable() {
	// public void run() {
	// showPopwindow();
	// search(); // search_Bounds();
	// InitApplication.getInstance().setHandler(mHandler);
	//
	// }
	// };

	// public void showPopwindow() {
	// if (mPopupWindow == null) {
	// LayoutInflater layoutInflater = (LayoutInflater)
	// (context).getSystemService(LAYOUT_INFLATER_SERVICE); //
	// // 获取自定义布局文件poplayout.xml的视图
	// View popview = layoutInflater.inflate(R.layout.progressbar, null);
	// mPopupWindow = new PopupWindow(popview, LayoutParams.WRAP_CONTENT,
	// LayoutParams.WRAP_CONTENT);
	// }
	// mPopupWindow.setFocusable(true);
	// mPopupWindow.setTouchable(false);
	// mPopupWindow.setBackgroundDrawable(new BitmapDrawable()); // 规定弹窗的位置
	// View view = findViewById(R.id.btnmap);
	// mPopupWindow.showAtLocation(view, Gravity.CENTER, 0, 0);
	// }
	//
	// public void closePopwindow() {
	// if (mPopupWindow != null) {
	// mPopupWindow.dismiss();
	// }
	// }

	/*
	 * 云检索发起
	 */
	private void search() {
		moreView.setVisibility(View.VISIBLE);
		// showPopwindow();
		// 云检索发起
		LBSCloudSearch.request_V2(getRequestParams_V2(), mHandler, InitApplication.networkType);
	}

	private HashMap<String, Object> getRequestParams_V2() {
		HashMap<String, Object> map = new HashMap<String, Object>();
		final Spinner spinner_region = (Spinner) findViewById(R.id.spinner_region);
		final Spinner spinner_nearby = (Spinner) findViewById(R.id.spinner_nearby);
		final Spinner spinner_type = (Spinner) findViewById(R.id.spinner_tags);
		final EditText edittext_search = (EditText) findViewById(R.id.edit_search);
		try {

			map.put("region", URLEncoder.encode("无锡", "utf-8"));
			map.put("TYPE", LBSCloudSearch.LOCAL_CODE);
			String query_str = edittext_search.getText().toString();
			// 过滤条件搜索
			if (!query_str.equals(null) && !query_str.equals("")) {
				map.put("q", query_str);
			}

			// 省市搜索
			if (spinner_region.getSelectedItemPosition() > 0) {
				String s1String = spinner_region.getSelectedItem().toString();
				map.put("region", URLEncoder.encode(s1String, "utf-8"));
				map.remove("TYPE");
				map.put("TYPE", LBSCloudSearch.LOCAL_CODE);
			}
			// 区域范围
			if (spinner_nearby.getSelectedItemPosition() > 0) {
				String s1String = spinner_nearby.getSelectedItem().toString();
				s1String = s1String.substring(0, s1String.length() - 1);
				map.remove("TYPE");
				map.remove("region");
				map.put("TYPE", LBSCloudSearch.NEARBY_CODE);
				map.put("radius", s1String);
				if (app.currlocation != null) {
					map.put("location", app.currlocation.getLongitude() + "," + app.currlocation.getLatitude());
				} else {
					// 无定位数据默认江阴
					double cLat = 31.925816;
					double cLon = 120.292073;
					map.put("location", cLon + "," + cLat);
				}
			}
			// 商家类型
			if (spinner_type.getSelectedItemPosition() > 0) {
				String s1String = spinner_type.getSelectedItem().toString();
				map.put("tags", s1String);
			}
			app.setFilterParams(map);

		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (NotFoundException e) {
			e.printStackTrace();
		}
		return map;
	}

	/*
	 * 解析返回数据
	 */
	private Handler tHandler = new Handler();
	private Runnable popRunnable;
	String comments;
	String likes;

	private void parser_V2(JSONObject json) {
		Eshop content = null;
		try {
			total = json.getInt("total");
			JSONArray jsonArray = json.getJSONArray("contents");
			if (jsonArray != null && jsonArray.length() <= 0) {
				Toast.makeText(context, "该地区范围内‘E消费’联盟商家正在洽谈中！", Toast.LENGTH_SHORT).show();
			} else {
				for (int i = 0; i < jsonArray.length(); i++) {
					JSONObject jsonObject2 = (JSONObject) jsonArray.opt(i);
					content = new Eshop();
					content.setGeotable_id(jsonObject2.optString("geotable_id"));
					content.setUid(jsonObject2.optString("uid"));
					content.setName(jsonObject2.getString("title"));
					content.setAddr(jsonObject2.getString("address"));
					content.setDistance(jsonObject2.getString("distance"));
					content.setImageurl(jsonObject2.optString("logo"));
					content.setPhone(jsonObject2.optString("phone"));
					content.setRating(jsonObject2.optString("rating"));
					content.setPrice(jsonObject2.optString("price"));
					content.setInfo(jsonObject2.optString("info"));

					// 计算距离
					JSONArray location = jsonObject2.getJSONArray("location");
					double latitude = (Double) location.get(1);
					double longitude = (Double) location.get(0);
					content.setLatitude(latitude);
					content.setLongitude(longitude);
					float results[] = new float[1];
					if (app.currlocation != null) {
						Location.distanceBetween(app.currlocation.getLatitude(), app.currlocation.getLongitude(), latitude, longitude, results);
					}
					content.setDistance("距离：" + (int) results[0] + "米");
					list.add(content);
				}
				// 百度地图索引页
				page_index++;
			}
			app.setList(list);
			count = list.size();
			progress.setVisibility(View.INVISIBLE);
		} catch (JSONException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 加载更多数据
	 */
	private void loadMoreData() {
		count = adapter.getCount();
		HashMap<String, Object> filterParams = InitApplication.getInstance().getFilterParams();
		filterParams.put("page_index", page_index);
		// showPopwindow();
		LBSCloudSearch.request_V2(filterParams, InitApplication.getInstance().getHandler(), InitApplication.networkType);
		count = list.size();
	}

	private int lastItem;

	@Override
	public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
		lastItem = firstVisibleItem + visibleItemCount - 1; // 减1是因为上面加了个addFooterView
	}

	@Override
	public void onScrollStateChanged(AbsListView view, int scrollState) {
		// 下拉到空闲是，且最后一个item的数等于数据的总数时，进行更新
		if (lastItem == count && scrollState == OnScrollListener.SCROLL_STATE_IDLE) {
			moreView.setVisibility(View.VISIBLE);
			scrollHandler.sendEmptyMessage(0);
		}
	}

	// 声明Handler
	private Handler scrollHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 0:
				loadMoreData(); // 加载更多数据，这里可以使用异步加载
				adapter.notifyDataSetChanged();
				if (count == total) {
					// closePopwindow();
					Toast.makeText(Test_TabListActivity.this, "没有更多数据！", 3000).show();
					// listView.removeFooterView(moreView); // 移除底部视图
				}
				break;
			case 1:
				break;
			default:
				break;
			}
		};
	};

	@Override
	public void onResume() {
		super.onResume();
		MobclickAgent.onResume(this);
	}

	@Override
	public void onPause() {
		super.onPause();
		MobclickAgent.onPause(this);
	}
}
